package com.ghh.encrypto;

import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

import oracle.security.jps.JpsException;

import org.apache.commons.codec.binary.Base64;

public class DESEncryptoService {
	private final static String algorithm = "DES";
	private FBLdiKeyStoreService kss;
	
	public DESEncryptoService() throws JpsException {
		kss = new FBLdiKeyStoreService();
	}
	
	public String encrypt(String plainText) throws Exception {
		SecretKey sKey = kss.getSecretKey();
		if (sKey == null) {
			sKey = generateKey();
			kss.saveSecretKey(sKey);
		}
		Cipher c1 = Cipher.getInstance(algorithm);
		c1.init(Cipher.ENCRYPT_MODE, sKey);
		byte[] encrytedData = c1.doFinal(plainText.getBytes());
		byte[] base64 = Base64.encodeBase64(encrytedData);
		String encryptedText = new String(base64);
		return encryptedText;
	}
	
	public String decrypt(String encryptText) throws Exception {
		SecretKey sKey = kss.getSecretKey();
		if (sKey == null) {
			throw new Exception("no secret key specified.");
		}
		Cipher c1 = Cipher.getInstance(algorithm);
		c1.init(Cipher.DECRYPT_MODE, sKey);
		byte[] b64 = encryptText.getBytes("UTF-8");
		byte[] encdata = Base64.decodeBase64(b64);
		byte[] plainBytes = c1.doFinal(encdata);
		return new String(plainBytes);
	}
	
	private SecretKey generateKey() throws NoSuchAlgorithmException {
//		DESKeySpec desKeySpec = new DESKeySpec(desKeyData);
//		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
//		SecretKey mySecretKey = keyFactory.generateSecret(desKeySpec);
		KeyGenerator kg = KeyGenerator.getInstance(algorithm);
		return kg.generateKey();
	}
	
	public static void main(String[] args) throws Exception {
		DESEncryptoService en = new DESEncryptoService();
		String ecp = en.encrypt("ASdasdasdsad 0adasd");
		System.out.println(ecp);
		System.out.println(en.decrypt(ecp));
		System.out.println(en.decrypt("BWHoogNuTG+R++rrQjc5L1WZunIAcAXT"));
	}
}
